import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Store from '../store'
import NotFound from '../views/Notfound.vue'

Vue.use(VueRouter)
Vue.use(Store)

const routes = [
  {
    path: '/',
    redirect: "/home"
  },
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    path: '/user',
    name: 'User',
    redirect: 'user/logout',
    component: () => import(/* webpackChunkName: "user" */ '../views/User.vue'),
    children: [
      {
        path: 'logout',
        name: 'Logout',
        component: () => import(/* webpackChunkName: "logout" */ '../components/user/Logout.vue')
      },
      {
        path: 'cart',
        name: "Cart",
        component: () => import( /* webpackChunkName: "center" */ '../components/user/Cart.vue')
      },
    ]
  },
  {
    path: '/order',
    name: 'Order',
    component: () => import( /* webpackChunkName: "order" */ '../views/Order.vue')
  },
  {
    path: '/free',
    name: 'Free',
    component: () => import( /* webpackChunkName: "free" */ '../views/Free.vue')
  },
  {
    path: '/particulars/:id',
    name: 'Particulars',
    component: () => import(/* webpackChunkName: "particulars" */ '../views/Particulars.vue')
  },
  {
    path: '/goods',
    name: 'Goods',
    component: () => import( /* webpackChunkName: "goods" */ '../views/Goods.vue')
  },
  {
    path: "*",
    component: NotFound
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/user') {
    let token = localStorage.getItem('x-auth-token')
    if (token) {
      next()
    } else {
      let obj = { content: "请先登录!", icon: "info" }
      Store.dispatch('AsyncToast', obj)
    }
    return
  }
  next()
})
export default router
